﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using DTO;
using DAO;

using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.OleDb;

namespace NhaTroService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class NhaTroService : INhaTroService
    {
        public string test(string json) {
            return json;
        }

        public string abc(string json) {
            return json;
        }
        public string GetData(string value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }

        #region INhaTroService Members


        public DuLieuDTO[] GetLisAlltNhaTro()
        {
            return new DuLieuDAO().getDuLieuByDichVu(20);
        }

        #endregion

        #region INhaTroService Members


        public DuLieuDTO[] GetNhaTroByQuan(string TenQuan)
        {
            int MaDichVu = 20;
            int MaQuan = int.Parse(new QuanDAO().getMaQuanByTenQuan(TenQuan));
            return new DuLieuDAO().getDuLieuByQuan(MaQuan,MaDichVu);
        }

        public DuLieuDTO[] GetNhaTroById(string MaNhaTro)
        {
            return new DuLieuDAO().getDuLieuById(long.Parse(MaNhaTro));
        }

        public DuLieuDTO[] GetNhaTroByPhuong(string TenPhuong)
        {
            int MaDichVu = 20;
            string strMaPhuong = new PhuongDAO().getMaTenPhuongByTenPhuong(TenPhuong);
            int MaPhuong = 0;
            if(strMaPhuong!="")
                MaPhuong = int.Parse(strMaPhuong);
            return new DuLieuDAO().getDuLieuByPhuong(MaPhuong,MaDichVu);
            
        }

        public DuLieuDTO[] GetNhaTroByDuong(string TenDuong)
        {
            int MaDichVu = 20;
            int MaPhuong = int.Parse(new DuongDAO().getMaTenDuongByTenDuong(TenDuong));
            return new DuLieuDAO().getDuLieuByPhuong(MaPhuong,MaDichVu);
            
        }
        
        #endregion

        #region INhaTroService Members

        /* Quy định format bên Client gửi tới là :
         * Do đã có filterEngine.js đảm nhận nên không sửa nữa, giữ nguyên format là :
         * cmd=<name>?MaDichVu=<Id>&TenDiaDiem=<name>&TenDuong=<name>
         * &TenPhuong=<name>&TenQuan=<name>
         * cmd=0&MaDichVu=1&TenDiaDiem=2&TenDuong=3&TenPhuong=4&TenQuan=5
         * 
         */
        public DuLieuDTO[] GetNhaTroBySearchText(string searchText)
        {
            //WebHttpSecurityMode.TransportCredentialOnly.
            string[] tmp = searchText.Split('-');
            string TenDiaDiems = tmp[2];
            string TenDuongs = tmp[3];
            string TenPhuongs = tmp[4];
            string TenQuans = tmp[5];
            string TenDiaDiem = TenDiaDiems.Split('=')[1];
            string TenDuong = TenDuongs.Split('=')[1];
            string TenPhuong = TenPhuongs.Split('=')[1];
            string TenQuan = TenQuans.Split('=')[1];

            int intMaDichVu = 20;
            int intMaDiaDiem = -1;
            int intMaDuong = -1;
            if (!TenDuong.Equals("null"))
            {
                string strMaDuong = new DuongDAO().getMaTenDuongByTenDuong(TenDuong);
                if (!strMaDuong.Equals(""))
                {
                    intMaDuong = int.Parse(strMaDuong);
                }
            }
            // Lấy Mã Phường theo Tên Phường nhập vào từ textbox(chuỗi querystring)
            int intMaPhuong = -1;
            if (!TenPhuong.Equals("null"))
            {
                string strMaPhuong = new PhuongDAO().getMaTenPhuongByTenPhuong(TenPhuong);
                if (!strMaPhuong.Equals(""))
                {
                    intMaPhuong = int.Parse(strMaPhuong);
                }
            }

            // Lấy Mã Quận theo Tên Quận nhập vào từ textbox
            int intMaQuan = -1;
            if (!TenQuan.Equals("null"))
            {
                string strMaQuan = new QuanDAO().getMaQuanByTenQuan(TenQuan);
                if (!strMaQuan.Equals(""))
                {
                    intMaQuan = int.Parse(strMaQuan);
                }
            }
            //System.Console.Write("{0-}{1-}{2-}{3-}{4-}",intMaDichVu,intMaQua);
            return new DuLieuDAO().getDulieuBy_DichVu_Duong_Quan(intMaDichVu, intMaDiaDiem, intMaDuong, intMaQuan);

        }

        #endregion
        public bool InsertNhaTro(string strJSONDULIEU)
        {
            
           
            CrossDomain();
            if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
                return false;
            else
            {
                if (WebOperationContext.Current.IncomingRequest.Method == "POST")
                {

                    //WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
                    //strJSONDULIEU = "{\"ChuThich\":\"A JSON\",\"KinhDo\":106.6891243,\"MaDichVu\":20,\"MaDuLieu\":99999,\"MaDuong\":410,\"MaPhuong\":146,\"MaQuanHuyen\":46,\"MaTenDiaDiem\":3526,\"MaTinhThanh\":16,\"SoNha\":\"218/4\",\"ViDo\":10.7774562}";
                    JavaScriptSerializer jSer = new JavaScriptSerializer();
                    DuLieuDTO dlDTO = jSer.Deserialize<DuLieuDTO>(strJSONDULIEU);

                    return new DuLieuDAO().insert2(dlDTO);
                }
                else
                    return false;
            }
        }

        public bool DeleteNhaTro(string MaNhaTro)
        {
            CrossDomain();
            if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
                return false;
            else
            {
                if (WebOperationContext.Current.IncomingRequest.Method == "DELETE")
                {
                    return new DuLieuDAO().delete(long.Parse(MaNhaTro));
                }
                else
                    return false;
            }
            
        }

        public bool UpdateNhaTro(string strJSONDULIEU)
        {

            CrossDomain();
            if(WebOperationContext.Current.IncomingRequest.Method=="OPTIONS")
                    return false;
            else 
            {
                if(WebOperationContext.Current.IncomingRequest.Method=="PUT")
                {
                       
                        //strJSONDULIEU = "{\"ChuThich\":\"BB JSON\",\"KinhDo\":106.6891243,\"MaDichVu\":20,\"MaDuLieu\":99999,\"MaDuong\":410,\"MaPhuong\":146,\"MaQuanHuyen\":46,\"MaTenDiaDiem\":3526,\"MaTinhThanh\":16,\"SoNha\":\"218/4\",\"ViDo\":10.7774562}";
                        JavaScriptSerializer jSer = new JavaScriptSerializer();
                        DuLieuDTO dlDTO = jSer.Deserialize<DuLieuDTO>(strJSONDULIEU);
                        return new DuLieuDAO().update(dlDTO);
                }
                else 
                    return false;
            }
        }

        private void CrossDomain()
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, PUT, DELETE");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
        }

        #region INhaTroService Members

        public bool ThemNhaTro(string value) {
            return InsertNhaTro(value);
        }

        public bool CapNhatNhaTro(string value) {
            return UpdateNhaTro(value);
        }
        #endregion

        #region INhaTroService Members


        public string GetLastID(string TenDD)
        {
            DiaDiemDAO ddDAO = new DiaDiemDAO();
            ddDAO.insert(TenDD);
            return ddDAO.getLastID();
        }
        public PhuongDTO[] GetListPhuong()
        {
            return new PhuongDAO().getAll();
        }

        public DuongDTO[] GetListDuong()
        {
            return new DuongDAO().getAll();
        }

        public string SearchDuong(string keyword)
        {

            OleDbConnection conn = new OleDbConnection(dataProvider._myConnectionString);
            OleDbCommand cmd = new OleDbCommand();
             
            cmd.CommandText = "select MaDuong,TenDuong from DUONG where " +
            "TenDuong like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", keyword);
            cmd.Connection = conn;
            StringBuilder sb = new StringBuilder();
            conn.Open();
            OleDbDataReader sdr = cmd.ExecuteReader();
            string strJSON = "[";
            while (sdr.Read())
            {
                strJSON += "{\"MaDuong\":" + sdr["MaDuong"] + ",\"TenDuong\":" + "\"" + sdr["TenDuong"] + "\"},";
                //sb.Append(sdr["MaDuong"] + "-" + sdr["TenDuong"])
                //    .Append(Environment.NewLine);
            }
            // Remove dấu phẩy cuối
            strJSON.Remove(strJSON.Length-1);
            strJSON += "]";
            conn.Close();
            return strJSON;

        }
        #endregion
    }
}
